package framework.io;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 路径列表匹配
 */
public class PathListMatcher {

    private final Map<String, String> fullMatchMap = new HashMap<>();
    private final List<String> startMatchList = new ArrayList<>();
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 初始化
     *
     * @param paths ant格式的规则列表
     */
    public PathListMatcher(List<String> paths) {
        for (String path : paths) {
            if (StringUtils.hasText(path)) {
                // 前导匹配
                if (this.antPathMatcher.isPattern(path)) {
                    startMatchList.add(path);
                }
                // 完全匹配
                else {
                    fullMatchMap.put(path, path);
                }
            }
        }
        //按路径长度排序
        startMatchList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.compare(o2.length(), o1.length());
            }
        });
    }

    /**
     * 匹配到的规则
     *
     * @param path
     * @return
     */
    public String match(String path) {
        if (!StringUtils.hasText(path)) return null;

        // 完全路径匹配
        String s = fullMatchMap.get(path);
        if (s != null) return s;

        // 前导匹配
        for (String fp : startMatchList) {
            if (this.antPathMatcher.match(fp, path)) {
                return fp;
            }
        }

        // 未找到
        return null;
    }
}